package web.server;

import java.io.PrintWriter;
import java.net.ServerSocket;
import java.util.Scanner;

public class EchoServer {
    public static void main(String[] args) {
        // establish a server socket
        try (ServerSocket serverSocket = new ServerSocket(Integer.parseInt(args[0]))) {
            // wait for a client to connect
            try (var clientSocket = serverSocket.accept()) {
                // read the client's message
                var input = clientSocket.getInputStream();
                var output = clientSocket.getOutputStream();
                try (Scanner in = new Scanner(input)) {
                    var out = new PrintWriter(output, true/* autoFlush */);
                    out.println("********************************");
                    out.printf("...Connected to %s:%d\n",
                            clientSocket.getInetAddress(), clientSocket.getPort());
                    out.println("*** Welcome to the Echo Server ***");
                    out.println("********************************");
                    out.println("Hello! Enter BYE to exit.");
                    while (in.hasNextLine()) {
                        var line = in.nextLine();
                        out.println("Received: " + line);
                        output.write(line.getBytes());
                        if (line.trim().equals("BYE")) {
                            out.println("Welcome back!");
                            System.exit(0);
                            break;
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
